<template>
  <div>
    <div ref="chartContainer" :style="{ width: '100%', height: '300px' }" />
  </div>
</template>

<script setup>
import { dataURLtoBlob } from "@/utils/common";
import * as echarts from "echarts";
import { computed, onUnmounted, ref, watch, onMounted, onBeforeUnmount } from "vue";

const chartContainer = ref(null);
let chartInstance = null;
const props = defineProps({
  chartsData: {
    type: Array,
    required: true
  }
});

const options = computed(() => {
  return {
    tooltip: {
      trigger: "item"
    },

    legend: {
      top: "5%",
      left: "center"
    },
    series: [
      {
        name: "",
        type: "pie",
        startAngle: 0,
        endAngle: 360,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2
        },
        // radius: props.type === "level" ? ["40%", "70%"] : "70%",
        radius: ["40%", "70%"],
        center: ["50%", "60%"],
        data: props.chartsData.map(item => ({
          name: item.typeName,
          value: item.count
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        },
        // color: props.type === "level" ? ["#E02B2B", "#FF771E", "#F1B11A", "#4A9BFF"] : ["#4472C5", "#ED7C30", "#80FF80", "#FF8096", "#800080"]
        color: ["#4786FF  ", "#14C7C7 ", "#FFB266 ", "#8B8AE6 "]
      }
    ]
  };
});
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    chartInstance.setOption(options.value);
  }
};
onMounted(() => {
  addResizeListener();
});
onBeforeUnmount(() => {
  removeResizeListener();
  if (chartInstance) {
    chartInstance.dispose();
  }
});
// 自适应函数（带防抖）
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 添加事件监听
const addResizeListener = () => {
  window.addEventListener("resize", handleResize);
};

// 移除事件监听
const removeResizeListener = () => {
  window.removeEventListener("resize", handleResize);
};
watch(
  () => props.chartsData,
  chartsData => {
    initChart();
  },
  {
    deep: true
  }
);
onUnmounted(() => {
  chartInstance && chartInstance.dispose();
});
</script>
